<!-- QQ登录: QQ账号绑定已有账号(手机号) src/views/login/components/QQLoginBindPhone.vue -->
<script setup lang="ts">
import { AuthAPI } from "@/api/AuthAPI";
import useCountdown from "@/logics/useCountdown";
import { useUserStore } from "@/stores/userStore";
import message from "@/utils/message";
import { toFormValidator } from "@vee-validate/zod";
import { AxiosError } from "axios";
import { Field, ErrorMessage } from "vee-validate";
import * as zod from "zod";
//接收传递的unionId
const props = defineProps<{ unionId: string }>();
// 获取用于存储用户信息的 store 对象
const userStore = useUserStore();
//用于储存QQ用户信息
const QQUserInfo = reactive({
  nickname: "",
  figureurl: "",
});
// 获取QQ用户的头像和昵称
window.QC.api("get_user_info").success(function (response: any) {
  //存储头像url
  QQUserInfo.figureurl = response.data.figureurl_1;
  //存储昵称
  QQUserInfo.nickname = response.data.nickname;
});
//表单验证规则
const validationSchema = toFormValidator(
  zod.object({
    mobile: zod
      .string({
        required_error: "请输入手机号",
        invalid_type_error: "手机号类型错误",
      })
      .regex(/^1[3-9]\d{9}$/, "请输入正确的手机号格式"),
    code: zod
      .string({
        required_error: "请输入验证码",
        invalid_type_error: "验证码类型错误",
      })
      .regex(/^\d{6}$/, "验证码格式错误"),
  })
);
const { handleSubmit, validateField, values } = useForm({
  validationSchema: validationSchema,
  initialValues: { mobile: "", code: "" },
});

const { count, isActive, start } = useCountdown();
// 发送手机验证码
async function sendMsgCode() {
  //验证用户是否填写了手机号
  let { valid } = await validateField("mobile");
  //验证未通过
  if (!valid) return;
  // 如果正在倒计时
  if (isActive.value) return;
  //捕获错误
  try {
    // 发送手机验证码
    await AuthAPI.sendMsgCodeOfBindQQ(values.mobile);
    message({ type: "success", msg: "验证码发送成功" });
    start(60);
  } catch (error) {
    //错误处理
    if (error instanceof AxiosError) {
      //消息提示
      message({ type: "error", msg: error.response?.data.message });
    } else if (error instanceof Error) {
      message({ type: "error", msg: "手机验证码发送失败" });
    }
  }
}

//表单提交
const onSubmit = handleSubmit((formValues) => {
  userStore.login(() =>
    AuthAPI.loginByBindAccount(
      formValues.mobile,
      formValues.code,
      props.unionId
    )
  );
});
</script>
<template>
  <form class="xtx-form" @submit.prevent="onSubmit">
    <div class="user-info">
      <img :src="QQUserInfo.figureurl" alt="" />
      <p>
        Hi, {{ QQUserInfo.nickname }}欢迎来小兔鲜,
        完成绑定后可以QQ账号一键登录哦~
      </p>
    </div>
    <div class="xtx-form-item">
      <Field name="mobile" as="div" v-slot="{ field }" class="field">
        <i class="icon iconfont icon-phone"></i>
        <input
          class="input"
          v-bind="field"
          type="text"
          placeholder="绑定的手机号"
        />
      </Field>
      <ErrorMessage as="div" name="mobile" class="error" v-slot="{ message }">{{
        message
      }}</ErrorMessage>
    </div>
    <div class="xtx-form-item">
      <Field name="code" as="div" v-slot="{ field }" class="field">
        <i class="icon iconfont icon-code"></i>
        <input
          class="input"
          v-bind="field"
          type="text"
          placeholder="短信验证码"
        />
        <span class="code" @click="sendMsgCode">
          {{ isActive ? `剩余${count}秒` : "发送验证码" }}</span
        >
      </Field>
      <ErrorMessage as="div" name="code" class="error" v-slot="{ message }">{{
        message
      }}</ErrorMessage>
    </div>
    <input type="submit" class="submit" value="立即绑定" />
  </form>
</template>

<style scoped lang="less">
.user-info {
  width: 320px;
  height: 70px;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin: 0 auto 20px;
  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }
  p {
    padding-left: 10px;
  }
}
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
